import { AppDispatch } from '@/store';
import { GetArticleByKeyWordApi, GetKeywordBysuggestApi } from '@/api/search';
import { ArtclesTypeAction } from '../reducer/search';
import { ClearKeyWordHistory } from '@/utils/storage';

/** 更新无限叠加文章列表 */
export function UpdateArticleByKeyWordAction(
  q: string,
  page?: number,
  per_page?: number
) {
  return async (dispatch: AppDispatch) => {
    let res = await GetArticleByKeyWordApi({ q, page, per_page });
    dispatch({ type: 'search/UpdateArticle', payload: res.data.results });
  };
}

/**清空搜索结果文章列表Action */
export function ClearArticleAction(): ArtclesTypeAction {
  return { type: 'search/ClearArticle' };
}

/** 根据关键字联想补全Action */
export function GetKeywordBysuggestAction(keyword: string) {
  return async (dispatch: AppDispatch) => {
    let res = await GetKeywordBysuggestApi(keyword);
    dispatch({ type: 'search/SaveSuggestion', payload: res.data.options });
  };
}

/**清空联想补全Action */
export function ClearsuggestAction(): ArtclesTypeAction {
  return { type: 'search/ClearSuggestion' };
}

/**保存搜索历史Action */
export function SaveKeyWordHistoryAction(keyword: string): ArtclesTypeAction {
  return { type: 'search/SaveKeyWordHistory', payload: keyword };
}

/**清空搜索历史Action */
export function ClearHistoriesAction(): ArtclesTypeAction {
  ClearKeyWordHistory();
  return { type: 'search/ClearHistory' };
}
